package com.xjk.encryp;

import java.security.MessageDigest;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * MD5摘要
 */
public class MD5Encrypt{

    /** UTF-8字符集 **/
    public static final String CHARSET_UTF8 = "UTF-8";

    /** MD5签名方式 */
    public static final String MD5 = "MD5";

    /** HMAC签名方式 */
    public static final String HMAC = "HmacMD5";

    /**
     * 对字符串采用UTF-8编码后，用MD5进行摘要。
     */
    public static byte[] encryptMD5(String data) throws Exception{
        return encryptMD5(data.getBytes(CHARSET_UTF8));
    }

    /**
     * 对字节流进行MD5摘要。
     */
    public static byte[] encryptMD5(byte[] data) throws Exception{
        MessageDigest md = MessageDigest.getInstance(MD5);
        return md.digest(data);
    }

    public static byte[] encryptHMAC(String data,String secret) throws Exception{
        SecretKey secretKey = new SecretKeySpec(secret.getBytes(CHARSET_UTF8), HMAC);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(data.getBytes(CHARSET_UTF8));
    }
}
